#!/usr/bin/perl

use Test;
BEGIN { plan tests => 16 }

$basedir = $0;
$basedir =~ s|(.*)/[^/]*|$1|;

# ================================================================= #
#  Basic Shared Memory Test Cases                                   #
# ================================================================= #
# First time should just get the resource
$output = `runcon -t test_ipc_base_t $basedir/shmget`;
ok( $?, 0 );
$output =~ /id = (\d+)$/ || print "Invalid output from shmget\n";
$ipcid = $1;

# Delete the resource
$output = `runcon -t test_ipc_base_t ipcrm shm $ipcid`;
ok( $?, 0 );

# Create it again
$output = `runcon -t test_ipc_base_t $basedir/shmget`;
ok( $?, 0 );
$output =~ /id = (\d+)$/ || print "Invalid output from shmget\n";
$ipcid = $1;

# Create it one more time to check associate permission
$output = `runcon -t test_ipc_base_t $basedir/shmget`;
ok( $?, 0 );
$output =~ /id = (\d+)$/ || print "Invalid output from shmget\n";
$ipcid2 = $1;

# Make sure they match
ok( $ipcid2, $ipcid );

# Try to associate with it from the unprivileged domain
$output = `runcon -t test_ipc_none_t $basedir/shmget`;
ok($?);
$output =~ /id = (\d+)$/ || print "Invalid output from shmget\n";
$ipcid = $1;

# ================================================================= #
# Shared Memory Control Tests (shmctl syscall)                      #
# ================================================================= #

# run shared memory control tests, we expect all to fail
$output = `runcon -t test_ipc_associate_t $basedir/shmctl`;
&reformat_results( $output, -1 );

# run shared memory control tests, we expect all to succeed
# last test should delete the object
$output = `runcon -t test_ipc_base_t $basedir/shmctl`;
&reformat_results( $output, 0 );

# ================================================================= #
# Shared Memory Operation Tests (shmat)                             #
# ================================================================= #

$output = `runcon -t test_ipc_base_t $basedir/shmat`;
ok( $?, 0 );

$output = `runcon -t test_ipc_associate_t $basedir/shmat`;
ok($?);    # -1

# Cleanup
$output = `runcon -t test_ipc_base_t $basedir/shmget`;
$output =~ /id = (\d+)$/ || print "Invalid output from shmget\n";
$ipcid  = $1;
$output = `runcon -t test_ipc_base_t ipcrm shm $ipcid`;

# ================================================================= #
# Miscellaneous Routines                                            #
# ================================================================= #
sub reformat_results {
    $list     = shift;
    $expected = shift;
    for ( split( ' ', $list ) ) {
        ok( $_, $expected );
    }
}
